<script setup>
  import { onBeforeUnmount, onMounted, ref } from 'vue'
  import { Clock, Coin, Delete, Document, Refresh } from '@element-plus/icons-vue'
  import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'
  import { getFileFontElement, shortName } from '@/utils/common.js'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { deleteFileService, recycleListService, restoreFileService } from '@/api/recycle.js'
  import Bus from '@/utils/bus.js'

  const fileList = ref([])

  // 右键菜单相关的响应式变量
  const showContextMenu = ref(false)
  const contextMenuX = ref(0)
  const contextMenuY = ref(0)
  const selectedFile = ref(null)

  const isLoading = ref(true)

  // 获取回收站文件列表
  const getRecycleList = async () => {
    isLoading.value = true
    try {
      const res = await recycleListService()
      fileList.value = res.data
    } catch (error) {
      console.error(error)
    } finally {
      isLoading.value = false
    }
  }

  const typeMatchingSvg = (filename, type) => {
    return getFileFontElement(filename, type)
  }

  // 处理还原文件
  const handleRestoreFiles = async files => {
    const fileIds = files.map(file => file.fileId)
    await restoreFileService(fileIds)
    ElMessage.success(files.length > 1 ? '文件已批量还原' : '文件已还原')
    // 清空选择
    multipleSelection.value = []
    tableRef.value?.clearSelection()
    // 刷新列表
    await getRecycleList()
  }

  // 处理彻底删除
  const handleDeleteFiles = async files => {
    const fileIds = files.map(file => file.fileId)
    await deleteFileService(fileIds)
    ElMessage.success(files.length > 1 ? '文件已批量删除' : '文件已删除')
    // 清空选择
    multipleSelection.value = []
    tableRef.value?.clearSelection()
    // 刷新列表
    await getRecycleList()
    Bus.emit('deleteFileSuccess')
  }

  // 确认还原对话框
  const handleRestoreConfirm = async files => {
    hideContextMenu()
    try {
      await ElMessageBox.confirm(
        files.length > 1
          ? `确认还原这 ${files.length} 个文件？`
          : `确认还原 "${shortName(files[0].filename)}"？`,
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      await handleRestoreFiles(files)
    } catch {
      // 用户取消操作
    }
  }

  // 确认删除对话框
  const handleDeleteConfirm = async files => {
    hideContextMenu()
    try {
      await ElMessageBox.confirm(
        files.length > 1
          ? `确认删除这 ${files.length} 个文件？此操作不可恢复！`
          : `确认删除 "${shortName(files[0].filename)}"？`,
        '警告',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'error'
        }
      )
      await handleDeleteFiles(files)
    } catch {
      // 用户取消操作
    }
  }

  // 处理右键点击事件
  const handleContextMenu = (row, column, event) => {
    event.preventDefault()

    const isSelected = multipleSelection.value.some(item => item.fileId === row.fileId)

    if (!isSelected) {
      multipleSelection.value = []
      tableRef.value?.clearSelection()
      tableRef.value?.toggleRowSelection(row, true)
      multipleSelection.value = [row]
    }

    selectedFile.value = row
    showContextMenu.value = true
    contextMenuX.value = event.clientX
    contextMenuY.value = event.clientY
  }

  // 处理菜单项点击
  const handleMenuClick = async action => {
    switch (action) {
      case 'restore':
        await handleRestoreConfirm(
          multipleSelection.value.length > 0 ? multipleSelection.value : [selectedFile.value]
        )
        break
      case 'delete':
        await handleDeleteConfirm(
          multipleSelection.value.length > 0 ? multipleSelection.value : [selectedFile.value]
        )
        break
    }
    hideContextMenu()
  }

  // 隐藏右键菜单
  const hideContextMenu = event => {
    if (event && event.target.closest('.context-menu')) {
      return
    }
    showContextMenu.value = false
    selectedFile.value = null
  }

  const multipleSelection = ref([])
  const handleSelectionChange = val => {
    multipleSelection.value = val
  }

  const tableRef = ref(null)
  const handleRowClick = (row, column) => {
    if (column.type === 'selection') return

    multipleSelection.value = []
    tableRef.value?.clearSelection()

    tableRef.value?.toggleRowSelection(row, true)
    multipleSelection.value = [row]
  }

  onMounted(() => {
    getRecycleList()
    document.addEventListener('click', hideContextMenu)
  })

  onBeforeUnmount(() => {
    try {
      document.removeEventListener('click', hideContextMenu)
    } catch (error) {
      console.error('移除事件监听器时出错:', error)
    }
  })
</script>

<template>
  <div class="page page-recycle">
    <el-alert :closable="false" show-icon title="回收站为你保存7天内删除的文件" type="warning">
    </el-alert>
    <!-- 文件列表 -->
    <el-card class="file-box no-select" @contextmenu.prevent>
      <el-scrollbar height="500px">
        <el-table
          ref="tableRef"
          v-loading="isLoading"
          :data="fileList"
          :row-style="{ height: '40px' }"
          element-loading-background="rgba(255, 255, 255, 0.9)"
          element-loading-text="数据加载中..."
          style="width: 100%; margin-top: 18px; cursor: pointer"
          @row-contextmenu="handleContextMenu"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @contextmenu.prevent
        >
          <template #empty>
            <el-empty description="回收站为空" />
          </template>
          <el-table-column type="selection" width="35" />
          <el-table-column label="文件名" min-width="40%">
            <template #header>
              <div style="display: flex; align-items: center">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Document />
                </el-icon>
                <span>文件名</span>
              </div>
            </template>
            <template #default="scope">
              <div class="file-item">
                <SvgIcon
                  :name="typeMatchingSvg(scope.row.filename, scope.row.fileType)"
                  height="22px"
                  width="22px"
                />
                <span class="filename">{{ shortName(scope.row.filename) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="删除时间" min-width="20%" prop="updateTime">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Clock />
                </el-icon>
                <span>删除时间</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="大小" min-width="10%" prop="fileSizeDesc">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Coin />
                </el-icon>
                <span>大小</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-card>

    <!-- 右键菜单 -->
    <div
      v-show="showContextMenu"
      :style="{ top: contextMenuY + 'px', left: contextMenuX + 'px' }"
      class="context-menu no-select"
      @contextmenu.prevent
    >
      <template v-if="selectedFile">
        <div class="menu-item" @click="handleMenuClick('restore')">
          <el-icon>
            <Refresh />
          </el-icon>
          <span>还原</span>
        </div>
        <div class="menu-item" @click="handleMenuClick('delete')">
          <el-icon>
            <Delete />
          </el-icon>
          <span>彻底删除</span>
        </div>
      </template>
    </div>
  </div>
</template>

<style lang="less" scoped>
  @import '@/assets/variable.less';

  .el-table {
    position: relative;
    min-height: 200px;
  }

  .file-item {
    display: flex;
    align-items: center;
    width: 100%;

    .filename {
      margin-left: 10px;
      line-height: 24px;
    }
  }

  .page-recycle {
    height: 100%;
  }

  .file-box {
    max-height: 620px;
    position: relative;
    margin-top: 12px;
    padding: 20px;
    flex: 1;
    background-color: #fff;
  }
</style>
